package dao

import (
	"context"
	"database/sql"
	"errors"
	"github.com/jackc/pgx/v5/pgconn"
	_ "gorm.io/driver/postgres"
	"gorm.io/gorm"
	"strings"
	"time"
)

var (
	ErrUserDuplicate = gorm.ErrDuplicatedKey
	ErrUserNotFind   = gorm.ErrRecordNotFound
)

type UserDao struct {
	db *gorm.DB
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		db: db,
	}
}

func (dao *UserDao) Insert(ctx context.Context, us Users) error {
	now := time.Now().UnixMilli()
	us.Ctime = now
	us.Utime = now
	err := dao.db.WithContext(ctx).Create(&us).Error
	var pgError *pgconn.PgError
	if errors.As(err, &pgError) {
		const code string = "23505"
		if strings.EqualFold(pgError.Code, code) {
			return ErrUserDuplicate
		}
	}
	return err
}

func (dao *UserDao) FindByEmail(ctx context.Context, email string) (Users, error) {
	var u Users
	err := dao.db.WithContext(ctx).Where("email=?", email).First(&u).Error
	return u, err

}

func (dao *UserDao) FindById(ctx context.Context, id int64) (Users, error) {
	var u Users
	err := dao.db.WithContext(ctx).Where("id=?", id).First(&u).Error
	return u, err
}

func (dao *UserDao) FindByPhone(ctx context.Context, phone string) (Users, error) {
	var u Users
	err := dao.db.WithContext(ctx).Where("phone=?", phone).First(&u).Error
	return u, err
}

func (dao *UserDao) FindByWechat(ctx context.Context, openID string) (Users, error) {
	var u Users
	err := dao.db.WithContext(ctx).Where("wechat_open_id = ?", openID).First(&u).Error
	//err := dao.p().WithContext(ctx).Where("wechat_open_id = ?", openID).First(&u).Error
	//err := dao.db.WithContext(ctx).First(&u, "email = ?", email).Error
	return u, err
}

type Users struct {
	Id       int64          `gorm:"primaryKey,autoIncrement"`
	Email    sql.NullString `gorm:"unique"`
	Password string
	Phone    sql.NullString `gorm:"unique"`
	Ctime    int64
	Utime    int64
}
